import { AxiosResponse, InternalAxiosRequestConfig } from './types'
import qs from 'qs'
import { objToFormData } from '@/utils'
import { TRANSFORM_REQUEST_DATA } from '@/constants'
import { token_set } from '@/utils/auth'
// import { SUCCESS_CODE, TRANSFORM_REQUEST_DATA } from '@/constants'
// import { useUserStoreWithOut } from '@/store/modules/user'
// import { ElMessage } from 'element-plus'

const defaultRequestInterceptors = (config: InternalAxiosRequestConfig) => {
  if (
    config.method === 'post' &&
    config.headers['Content-Type'] === 'application/x-www-form-urlencoded'
  ) {
    config.data = qs.stringify(config.data)
  } else if (
    TRANSFORM_REQUEST_DATA &&
    config.method === 'post' &&
    config.headers['Content-Type'] === 'multipart/form-data' &&
    !(config.data instanceof FormData)
  ) {
    config.data = objToFormData(config.data)
  }
  if (config.method === 'get' && config.params) {
    let url = config.url as string
    url += '?'
    const keys = Object.keys(config.params)
    for (const key of keys) {
      if (config.params[key] !== void 0 && config.params[key] !== null) {
        url += `${key}=${encodeURIComponent(config.params[key])}&`
      }
    }
    url = url.substring(0, url.length - 1)
    config.params = {}
    config.url = url
  }
  return config
}

const defaultResponseInterceptors = (response: AxiosResponse) => {
  // if (response?.config?.responseType === 'blob') {
  //   // 如果是文件流，直接过
  //   return response
  // } else if (response.data.code === SUCCESS_CODE) {
  //   return response.data
  // } else {
  //   ElMessage.error(response?.data?.message)
  //   if (response?.data?.code === 401) {
  //     const userStore = useUserStoreWithOut()
  //     userStore.logout()
  //   }
  // }
  const data = response.data
  if (data.MsgCode !== undefined) {
    const tokenData = response.headers['Set-Token']
    if (tokenData) {
      token_set(tokenData)
    } else {
      const tokenData2 = response.headers['set-token']
      if (tokenData2) {
        token_set(tokenData2)
      }
    }
    // 验证令牌码
    const tmpCode = parseInt(data.MsgCode)
    if (tmpCode === 50002 || tmpCode === 50006 || tmpCode === 50013) {
      if (response.request.responseURL.indexOf('Api/FALogin/Login') < 0) {
        // store.dispatch('common/resetToken').then(() => {
        //   location.reload()
        //   // localStorage.setItem(LS_SYSTEM_MESSAGE_CODE, 0)
        // })
      }
    } else if (tmpCode === 50005 || tmpCode === 50010 || tmpCode === 50012) {
      // store.dispatch('common/resetToken').then(() => {
      //   location.reload()
      //   // localStorage.setItem(LS_SYSTEM_MESSAGE_CODE, 1)
      // })
    }
  }
  return data
}

export { defaultResponseInterceptors, defaultRequestInterceptors }
